const Router = require("koa-router");
const router = new Router();
const db = require("../db");


router.post("/api/add/address",async (ctx,next)=>{
    let {userid,address,city,user,tel,active} = ctx.request.body;
    
    //查询是否有数据
    let findData = await db.select(`select * from addresslist where userid=${userid}`);
    if(findData.length==0){ //如果没有数据默认添加第一条数据是默认选中得
        let res = await db.add(`insert into addresslist (userid,user,tel,city,address,active) values (
            "${userid}","${user}","${tel}","${city}","${address}","true"
        )`)
        if(res==0){
            ctx.body = {
                code:0,
                msg:"添加成功"
            }
        }else{
            ctx.body = {
                code:1,
                msg:"添加失败"
            }
        }
    }else{
        if(active=="true"){ //如果设置默认则把数据库中另一条为默认得取消
           let updateres = await db.update(`update addresslist set active='false' where userid=${userid} and active='true'`);
           if(updateres==0){
            let res = await db.add(`insert into addresslist (userid,user,tel,city,address,active) values (
                "${userid}","${user}","${tel}","${city}","${address}","${active}"
            )`)
            if(res==0){
                ctx.body = {
                    code:0,
                    msg:"添加成功"
                }
            }else{
                ctx.body = {
                    code:1,
                    msg:"添加失败"
                }
            }
           }
        }else{
            let res = await db.add(`insert into addresslist (userid,user,tel,city,address,active) values (
                "${userid}","${user}","${tel}","${city}","${address}","${active}"
            )`)
            if(res==0){
                ctx.body = {
                    code:0,
                    msg:"添加成功"
                }
            }else{
                ctx.body = {
                    code:1,
                    msg:"添加失败"
                }
            }
        }
        
    }
    
})


router.get("/api/address/:userid",async (ctx,next)=>{
    let {userid} = ctx.params;
    let data = await db.select(`select * from addresslist where userid=${userid}`);
    ctx.body = {
        code:0,
        data:data
    }
})


router.get("/api/default/address/:userid",async (ctx,next)=>{
    let {userid} = ctx.params;
    let data = await db.select(`select * from addresslist where userid=${userid} and active="true"`);
    ctx.body = {
        code:0,
        data:data[0]
    }
})


router.get("/api/edit/address/:id",async (ctx,next)=>{
     let {id} = ctx.params;
     let data = await db.select(`select * from addresslist where id=${id}`);
     ctx.body = {
        code:0,
        data:data[0]
    }

})


module.exports = router;